
from tornado.web import RequestHandler, asynchronous
from tornado.httpclient import AsyncHTTPClient,HTTPClient, HTTPResponse, HTTPRequest


# 处理证书认证
import ssl
ssl._create_default_https_context = ssl._create_unverified_context()

# 同步
class DownloadHandler(RequestHandler):
    def get(self):
        # 获取查询参数中url（下载资源的网址）
        url = self.get_query_argument('url')
        filename = self.get_query_argument('filename','index.html')

        # 发起同步请求
        client = HTTPClient()
        # 关闭验证证书validate_cert = False
        response:HTTPResponse = client.fetch(url, validate_cert=True)

        # 1、在控制台输出
        # print(response.body)

        # 2、 保存到static.downloads
        from app import BASE_DIR, os
        download_dir = os.path.join(BASE_DIR, 'static/downloads')
        with open(os.path.join(download_dir,filename),'wb') as f:
            f.write(response.body)

        self.write('下载成功')


# 异步
class AsyncDownloadHandler(RequestHandler):
    def save(self, response: HTTPResponse):
        print(response.effective_url)
        self.write('<br>下载完成，正在保存')

        # 在回调函数中，可以获取请求查询的参数
        filename = self.get_query_argument('filename', 'index.html')

        # 2、 保存到static.downloads
        from app import BASE_DIR, os
        download_dir = os.path.join(BASE_DIR, 'static/downloads')
        with open(os.path.join(download_dir, filename), 'wb') as f:
            f.write(response.body)

        self.write('保存文件成功！')
        self.finish()

    @asynchronous
    def get(self):
        # 获取查询参数中url（下载资源的网址）
        url = self.get_query_argument('url')


        # 发起同步请求
        client = AsyncHTTPClient()

        client.fetch(url,callback=self.save,validate_cert=True)

        self.write('下载中')
        self.set_status(200)


# 改成协程写法
class Async2DownloadHandler(RequestHandler):
    def save(self,response:HTTPResponse):
        print(response.effective_url)
        self.write('<br>下载完成，正在保存')

        # 在回调函数中，可以获取请求查询的参数
        filename = self.get_query_argument('filename', 'index.html')

        # 2、 保存到static.downloads
        from app import BASE_DIR, os
        download_dir = os.path.join(BASE_DIR, 'static/downloads')
        with open(os.path.join(download_dir, filename), 'wb') as f:
            f.write(response.body)

        self.write('保存文件成功！')
        self.finish()

    @asynchronous
    async def get(self):
        # 获取查询参数中url（下载资源的网址）
        url = self.get_query_argument('url')


        # 发起同步请求
        client = AsyncHTTPClient()

        response = await client.fetch(url,
                     validate_cert=True)

        self.write('下载中')
        self.set_status(200)